package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.item.client.ItemFeignClient;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

/**
 * @program: gmall-parent
 * @author: Mr.Zhuo
 * @create: 2022-04-06 14:38
 **/
@Controller
public class ItemController {

    @Autowired
    private ItemFeignClient itemFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private TemplateEngine templateEngine;

    @RequestMapping("{skuId}.html")
    public String getItem(@PathVariable Long skuId, Model model) {
        // 通过skuId 查询skuInfo
        Result<Map> result = itemFeignClient.getBySkuId(skuId);
        model.addAllAttributes(result.getData());
        return "item/item";
    }

    @RequestMapping(value = {"/", "index.html"})
    public String index(Model model) {

        // 远程调用数据
        Result result = productFeignClient.getBaseCategoryList();

        // 然后保存数据
        model.addAttribute("list", result.getData());

        // 进行页面跳转
        return "index/index";
    }

    @RequestMapping("createIndex")
    @ResponseBody
    public Result createIndex() {

        // 远程调用属性
        Result result = productFeignClient.getBaseCategoryList();

        // 设置模板的内容
        Context context = new Context();
        context.setVariable("list", result.getData());

        // 输出到哪里
        FileWriter writer = null;
        try {
            writer = new FileWriter("D:\\index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //templateEngine
        templateEngine.process("index/index.html", context, writer);

        return Result.ok();
    }


}
